package com.wangjiang.mario.admin.core.aspectj;


import com.alibaba.fastjson.JSONObject;
import com.wangjiang.mario.admin.common.annotation.LogTrack;
import com.wangjiang.mario.admin.common.util.DateUtil;
import com.wangjiang.mario.admin.common.util.ServletUtils;
import com.wangjiang.mario.admin.common.util.StringUtils;
import com.wangjiang.mario.admin.core.manager.AsyncManager;
import com.wangjiang.mario.admin.core.manager.factory.AsyncFactory;
import com.wangjiang.mario.admin.core.shiro.utils.ShiroUtils;
import com.wangjiang.mario.admin.system.domain.entity.LogEntity;
import com.wangjiang.mario.admin.system.object.user.UserRoleMenuVo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;


/**
 * 数据过滤处理
 *
 */
@Aspect
@Component
public class LogTrackAspect {
    private static final Logger log = LoggerFactory.getLogger(LogTrackAspect.class);

    // 配置织入点
    @Pointcut("@annotation(com.wangjiang.mario.admin.common.annotation.LogTrack)")
    public void logPointCut()
    {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint)
    {
        handleLog(joinPoint, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e)
    {
        handleLog(joinPoint, e);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e)
    {
        try
        {
            // 获得注解
            LogTrack controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null)
            {
                return;
            }

            // 获取当前的用户
            UserRoleMenuVo currentUser = ShiroUtils.getCurrentUser();

            // *========数据库日志=========*//
            LogEntity operLog = new LogEntity();
            operLog.setLogType(0);
            // 请求的地址
            HttpServletRequest request = ServletUtils.getRequest();
            String ip = request.getRemoteAddr();
            System.out.println(ip);
            operLog.setRequestIp(ip);

            operLog.setRequestUri(request.getRequestURI());
            operLog.setUserAgent(request.getHeader("user-agent"));
            if (currentUser != null)
            {
                operLog.setUserName(currentUser.getLoginName());
            }

            if (e != null)
            {
                operLog.setLogType(1);
                // TODO
                operLog.setExceptionCode("500");
                operLog.setExceptionDetail(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setRequestBody(JSONObject.toJSONString(joinPoint.getArgs()));
            operLog.setMethodName(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operLog);
            operLog.setCreatedTime(DateUtil.getNowDate());
            operLog.setCreatedByName(currentUser.getLoginName());
            operLog.setCreatedById(currentUser.getUuid());
            operLog.setDelFlag(false);
            operLog.setStatus(true);
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        }
        catch (Exception exp)
        {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log 日志
     * @param operLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(LogTrack log, LogEntity operLog) throws Exception
    {
        // 设置action动作
//        operLog.setBusinessType(log.businessType().ordinal());
        // 设置标题
        operLog.setOperation(log.title());
        // 设置操作人类别
//        operLog.setOperatorType(log.operatorType().ordinal());
        // 是否需要保存request，参数和值
//        if (log.isSaveRequestData())
//        {
        // 获取参数的信息，传入到数据库中。
        setRequestValue(operLog);
//        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(LogEntity operLog) throws Exception
    {
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        String params = JSONObject.toJSONString(map);
        operLog.setRequestParams(StringUtils.substring(params, 0, 2000));
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private LogTrack getAnnotationLog(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(LogTrack.class);
        }
        return null;
    }
}
